package cn.uyunsky.platform.util.sql;


/**
 * <p>Description: 拥有缓存效果的sql解析工厂:类似org.hibernate.engine.query.QueryPlanCache</p>
 * <li>从缓存中获取已解析的nameSql
 * <li>缓存中没有则即使创建
 * @version 1.0
 * @author baiyh
 */
public class SqlPlanFactory {
	
	private static SqlPlanFactory instance = new SqlPlanFactory();
	public static SqlPlanFactory getInstance() {
		return instance;
	}

	/**
	 * @Fields planCache : 原始sql与解析缓存对照关系
	 */
	private SimpleMRUCache planCache = new SimpleMRUCache(1024);
	
	//如果没有则需要解析
	public SqlPlan getPlanCache(String nameSql) {
		SqlPlan sqlplan = (SqlPlan) planCache.get(nameSql);
		if (sqlplan == null) {
			sqlplan = new SqlPlan(nameSql);
			planCache.put(nameSql, sqlplan);
		}
		return sqlplan;
	}
	
	public static void main(String[] args) {
		String sql = "select userid,to_char(createTime,'YYYY-MM-DD HH24:mm:ss') from mypersion where namea2= :name and age>:age1 and age<:age2 and name = :name2";
		long start1 = System.currentTimeMillis();
		SqlPlan sqlplan = SqlPlanFactory.getInstance().getPlanCache(sql);
		System.out.println(sqlplan.getPlanSql());
		System.out.println(sqlplan.getNameList());
		
		long start2 =  System.currentTimeMillis();
		System.out.println(start2-start1);
		
		sqlplan = SqlPlanFactory.getInstance().getPlanCache(sql);
		System.out.println(sqlplan.getPlanSql());
		System.out.println(sqlplan.getNameList());
		System.out.println( System.currentTimeMillis()-start2);
	}

}
